package com.jk.controller;

import com.jk.entity.StaffEntity;
import com.jk.service.Impl.LoginServiceImpl;

import com.jk.utils.Md5UUIDSaltUtil;
import com.jk.utils.MsgUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("login")
@RestController
@CrossOrigin(origins = "*")
public class LoginController {
    @Autowired
    LoginServiceImpl loginService;

    //通过java去操作redis缓存string类型的数据
    @Resource
    private RedisTemplate redisTemplate;

    //需要权限为ROLE_USER才能访问/index

    @GetMapping("index")
    public String index(@RequestHeader String token){
        return "hello";
    }

    //需要权限ROLE_ADMIN才能访问hello
    @RequiresPermissions("ROLE_ADMIN")
    @GetMapping("hello")
    public String hello(@RequestHeader String token){
        return "注销成功";
    }

    //登录接口
    @PostMapping("login")
    public Map login(@RequestParam("username")String username, @RequestParam("password")String password){
        StaffEntity staff = loginService.findByUsername(username);

        if (staff == null) {
            return MsgUtil.returnMsg(250,"账号错误",null);
        } else {
            String salt = staff.getSalt();
            String mySalt = salt.substring(0, 5);
            String md5Code = Md5UUIDSaltUtil.createMd5Code(password + mySalt);
            if (!staff.getPassword().equals(md5Code)) {
                return MsgUtil.returnMsg(251, "密码错误", null);
            } else {
                //通过UUID生成token字符串,并将其以string类型的数据保存在redis缓存中，key为token，value为username
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                redisTemplate.opsForValue().set(token, username, 3600, TimeUnit.SECONDS);
                staff.setToken(token);
                staff.setPassword(password);
                return MsgUtil.returnMsg(200, "登陆成功", staff);
            }
        }
    }
    //修改密码
    @RequestMapping("updatePwd")
    public void updatePwd(StaffEntity staff){
        loginService.updatePwd(staff);
    }


    //注销接口
    @PostMapping("logout")
    public String logout(@RequestHeader("token")String token){
        //删除redis缓存中的token
        redisTemplate.delete(token);
        return "注销成功";
    }

}
